package com.itump.base.util;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.SequenceGenerator;
import org.hibernate.type.Type;

/**
 *  
 * 作者：itump<br>
 * 功能描述: 用于Hibernate中，自动根据规则产生序列号(在.hbm.xml文件中配置)。<br>
 * 规则是：前缀 + n位流水号<br>
 * 用法示例：<br>
 * 
 * <pre>
 *<id name="roleid" column="ROLEID" type="string">
 *           <generator class="com.itump.××">
 *          	<param name="sequence">IMS.SQ_FP_ROLE</param>
 *          	<param name="prefix">RL</param>
 *          	<param name="post">000000000</param>
 *          </generator>
 * </id>
 * </pre>
 * 如果前缀是 $CURRENT_YEAR_MONTH，则将使用当前年月作为前缀，后缀仍然是n位流水号。
 
 */
public class FpSequenceGenerator extends SequenceGenerator {

	private String prefix;
	private String post;
	private static final SimpleDateFormat ymFormat = new SimpleDateFormat(
			"yyyyMM");
	private static final String YmPrefix = "$CURRENT_YEAR_MONTH";

	public void configure(Type type, Properties params, Dialect d)
			throws MappingException {
		super.configure(type, params, d);
		prefix = params.getProperty("prefix");
		post = params.getProperty("post");
	}

	public Serializable generate(SessionImplementor session, Object obj)
			throws HibernateException {
		Serializable result = super.generate(session, obj);
		if (post != null) {
			DecimalFormat format = new DecimalFormat(post);
			if (prefix != null && !prefix.trim().equals("")) {
				String r = null;
				// 以年月为前缀
				if (YmPrefix.equals(prefix.trim())) {
					r = ymFormat.format(new Date())
							+ format.format(Long.parseLong(result.toString()));
				} else {
					r = prefix
							+ format.format(Long.parseLong(result.toString()));
				}
				return r;
			}
		}
		return result;
	}

}
